import Taro, { Component } from '@tarojs/taro'
import classnames from 'classnames'
import PropsType from 'prop-types'
import { View } from '@tarojs/components'
import '../styles/infotime.scss'

class DInfotime extends Component {

    constructor(props) {
        super(props)
        this.state = {
            time: 60,
            text: '',
            // disabled: false
        }
    }

    componentWillMount() {
        const { time = 60, firstText } = this.props
        this.setState({
            time,
            text: firstText,
            // disabled
        })
    }

    onTimeHandle() {
        let { time, text } = this.state
        const { disabled } = this.props
        if (disabled) {
            return
        }
        let _time = setInterval(() => {
            time--
            if (time === 0) {
                const { newText } = this.props
                text = newText
                return this.setState({
                    text,
                    // disabled: false
                }, () => {
                    const agr = {
                        status: false
                    }
                    this.props.onTimeHandle && this.props.onTimeHandle(agr)
                    clearInterval(_time)
                })
            }
            this.setState({
                text: time + 's',
                // disabled: true
            }, () => {
                const agr = {
                    status: true
                }
                this.props.onTimeHandle && this.props.onTimeHandle(agr)
            })
        }, 1000)
    }

    render() {
        const {
            className
        } = this.props
        const {
            text,
            disabled
        } = this.state
        return (
            <View onClick={this.onTimeHandle.bind(this)} className={classnames('b_infotime', disabled ? 'b_infotime--disabled' : '', className)}>
                {text}
            </View>
        )
    }

}

DInfotime.defaultProps = {
    className: '',
    time: 60,
    disabled: false,
    firstText: '获取验证码',
    newText: '重新获取验证码'
}

DInfotime.PropsType = {
    className: PropsType.oneOfType[PropsType.string, PropsType.object],
    time: PropsType.number,
    disabled: PropsType.bool,
    firstText: PropsType.string,
    newText: PropsType.string
}

export default DInfotime